<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="站点id" prop="mid">
              <el-input v-model="queryParams.mid" placeholder="请输入站点id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="店铺名" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入店铺名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="亚马逊店铺id" prop="sellerId">
              <el-input v-model="queryParams.sellerId" placeholder="请输入亚马逊店铺id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="店铺账户名称" prop="accountName">
              <el-input v-model="queryParams.accountName" placeholder="请输入店铺账户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="店铺账号id" prop="sellerAccountId">
              <el-input v-model="queryParams.sellerAccountId" placeholder="请输入店铺账号id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="站点简称" prop="region">
              <el-input v-model="queryParams.region" placeholder="请输入站点简称，例如NA指北美" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="商城所在国家名称" prop="country">
              <el-input v-model="queryParams.country" placeholder="请输入商城所在国家名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['lingxing:sellerInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['lingxing:sellerInfo:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['lingxing:sellerInfo:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['lingxing:sellerInfo:export']">导出</el-button>
          </el-col>-->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleSyncData">同步数据</el-button>
          </el-col>
          <el-col :span="15">
            数据更新时间：
            <el-text>{{ newestUpdateTime }}</el-text>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="sellerInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="true" label="店铺id" align="center" prop="sid" />
        <el-table-column label="站点id" align="center" prop="mid" />
        <el-table-column label="店铺名" align="center" prop="name" />
        <el-table-column label="亚马逊店铺id" align="center" prop="sellerId" />
        <el-table-column label="店铺账户名称" align="center" prop="accountName" />
        <el-table-column label="店铺账号id" align="center" prop="sellerAccountId" />
        <el-table-column label="站点简称" align="center" prop="region" />
        <el-table-column label="商城所在国家名称" align="center" prop="country" />
        <el-table-column label="是否授权广告" align="center" prop="hasAdsSetting" />
        <el-table-column label="市场id" align="center" prop="marketplaceId" />
        <el-table-column label="店铺状态" align="center" prop="status" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['lingxing:sellerInfo:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['lingxing:sellerInfo:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改领星亚马逊店铺对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="sellerInfoFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="站点id" prop="mid">
          <el-input v-model="form.mid" placeholder="请输入站点id" />
        </el-form-item>
        <el-form-item label="店铺名" prop="name">
          <el-input v-model="form.name" placeholder="请输入店铺名" />
        </el-form-item>
        <el-form-item label="亚马逊店铺id" prop="sellerId">
          <el-input v-model="form.sellerId" placeholder="请输入亚马逊店铺id" />
        </el-form-item>
        <el-form-item label="店铺账户名称" prop="accountName">
          <el-input v-model="form.accountName" placeholder="请输入店铺账户名称" />
        </el-form-item>
        <el-form-item label="店铺账号id" prop="sellerAccountId">
          <el-input v-model="form.sellerAccountId" placeholder="请输入店铺账号id" />
        </el-form-item>
        <el-form-item label="站点简称，例如NA指北美" prop="region">
          <el-input v-model="form.region" placeholder="请输入站点简称，例如NA指北美" />
        </el-form-item>
        <el-form-item label="商城所在国家名称" prop="country">
          <el-input v-model="form.country" placeholder="请输入商城所在国家名称" />
        </el-form-item>
        <el-form-item label="是否授权广告：0 否 1 是" prop="hasAdsSetting">
          <el-input v-model="form.hasAdsSetting" placeholder="请输入是否授权广告：0 否 1 是" />
        </el-form-item>
        <el-form-item label="市场id" prop="marketplaceId">
          <el-input v-model="form.marketplaceId" placeholder="请输入市场id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SellerInfo" lang="ts">
import {
  listSellerInfo,
  getSellerInfo,
  delSellerInfo,
  addSellerInfo,
  updateSellerInfo,
  syncData,
  getNewestUpdateTime
} from '@/api/lingxing/sellerInfo';
import { SellerInfoVO, SellerInfoQuery, SellerInfoForm } from '@/api/lingxing/sellerInfo/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const sellerInfoList = ref<SellerInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const sellerInfoFormRef = ref<ElFormInstance>();
const newestUpdateTime = ref('');

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SellerInfoForm = {
  sid: undefined,
  mid: undefined,
  name: undefined,
  sellerId: undefined,
  accountName: undefined,
  sellerAccountId: undefined,
  region: undefined,
  country: undefined,
  hasAdsSetting: undefined,
  marketplaceId: undefined,
  status: undefined
};
const data = reactive<PageData<SellerInfoForm, SellerInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    mid: undefined,
    name: undefined,
    sellerId: undefined,
    accountName: undefined,
    sellerAccountId: undefined,
    region: undefined,
    country: undefined,
    hasAdsSetting: undefined,
    marketplaceId: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    sid: [{ required: true, message: '店铺id不能为空', trigger: 'blur' }],
    mid: [{ required: true, message: '站点id不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '店铺名不能为空', trigger: 'blur' }],
    sellerId: [{ required: true, message: '亚马逊店铺id不能为空', trigger: 'blur' }],
    accountName: [{ required: true, message: '店铺账户名称不能为空', trigger: 'blur' }],
    sellerAccountId: [{ required: true, message: '店铺账号id不能为空', trigger: 'blur' }],
    region: [{ required: true, message: '站点简称，例如NA指北美不能为空', trigger: 'blur' }],
    country: [{ required: true, message: '商城所在国家名称不能为空', trigger: 'blur' }],
    hasAdsSetting: [{ required: true, message: '是否授权广告：0 否 1 是不能为空', trigger: 'blur' }],
    marketplaceId: [{ required: true, message: '市场id不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '店铺状态：0 停止同步 1 正常 2 授权异常 3 欠费停服不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询领星亚马逊店铺列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSellerInfo(queryParams.value);
  sellerInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;

  const res1 = await getNewestUpdateTime();
  newestUpdateTime.value = res1.msg;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  sellerInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: SellerInfoVO[]) => {
  ids.value = selection.map((item) => item.sid);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加领星亚马逊店铺';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SellerInfoVO) => {
  reset();
  const _sid = row?.sid || ids.value[0];
  const res = await getSellerInfo(_sid);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改领星亚马逊店铺';
};

/** 提交按钮 */
const submitForm = () => {
  sellerInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.sid) {
        await updateSellerInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addSellerInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: SellerInfoVO) => {
  const _sids = row?.sid || ids.value;
  await proxy?.$modal.confirm('是否确认删除领星亚马逊店铺编号为"' + _sids + '"的数据项？').finally(() => (loading.value = false));
  await delSellerInfo(_sids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'lingxing/sellerInfo/export',
    {
      ...queryParams.value
    },
    `sellerInfo_${new Date().getTime()}.xlsx`
  );
};

/** 同步数据按钮操作 */
const handleSyncData = async (row?: SellerInfoVO) => {
  loading.value = true;
  await proxy?.$modal.confirm('是否同步领星亚马逊卖家数据项？').finally(() => (loading.value = false));
  loading.value = true;
  await syncData(queryParams.value).finally(() => (loading.value = false));
  proxy?.$modal.msgSuccess('同步数据成功!');
  loading.value = true;
  await getList().finally(() => (loading.value = false));
};

onMounted(() => {
  getList();
});
</script>
